package com.monitor.module.camera.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.monitor.entity.pojo.camera.Camera;
import com.monitor.entity.pojo.user.User;
import com.monitor.entity.request.camera.CameraFindRequest;
import com.monitor.entity.request.camera.CameraRequest;
import com.monitor.entity.response.ResultCode;
import com.monitor.entity.response.Rs;
import com.monitor.module.camera.service.CameraService;
import com.monitor.utils.PoJoUtil;
import com.monitor.utils.SnowflakeIdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 摄像头接口.
 *
 * @author Li Zhiyuan
 * @since 2020-11-17
 */
@RestController
@RequestMapping("/camera")
@Slf4j
@Api(tags = "摄像头接口")
public class CameraController {
    @Autowired
    private CameraService service;
    @Resource
    private RedisTemplate<String, User> redisTemplate;

    /**
     * 摄像头绑定企业账号（项目名称占时没有）以及出入口
     */
    @PostMapping("/binding")
    @ApiOperation(value = "绑定", notes = "摄像头绑定企业账号")
    public ResponseEntity<Rs<Object>> binding(@RequestBody @Valid CameraRequest request) {
        if (service.list(Wrappers.<Camera>lambdaQuery().eq(Camera::getMac, request.getMac())).size() != 0)
            return Rs.fail(ResultCode.DUPLICATEUNIQUEID);
        request.setEntryId(SnowflakeIdWorker.getId());
        service.save(PoJoUtil.transToPoJo(request, Camera.class));
        return Rs.ok(ResultCode.BINDING);
    }

    /**
     * 查询摄像头绑定信息
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询摄像头信息", notes = "摄像头信息查询可以根据mac搜索和企业名称搜索")
    public ResponseEntity<Rs<Object>> list(CameraFindRequest request) {
        return Rs.ok(Rs.map().put("data", service.list(Wrappers.<Camera>lambdaQuery().eq(request.getMac() != null, Camera::getMac, request.getMac())
                .eq(request.getCompanyId() != null, Camera::getCompanyId, request.getCompanyId()))));
    }

    /**
     * 查询企业账号绑定的所有项目名称
     */
    @GetMapping()
    @ApiOperation(value = "查询项目名称", notes = "查询企业账号绑定的所有项目名称")
    public ResponseEntity<Rs<Object>> getEntryName(HttpServletRequest request) {
        Long companyId = redisTemplate.opsForValue().get(request.getHeader("token")).getCompanyId();
        return Rs.ok(Rs.map().put("data", service.list(new QueryWrapper<Camera>()
                .select("DISTINCT `entry_name`").lambda().eq(Camera::getCompanyId, companyId))));
    }

}
